#!/usr/bin/env python
#coding=utf-8
# from __future__ import print_function
import roslib
# roslib.load_manifest('my_package')
import sys
import rospy
import random
import argparse
import imutils
import cv2
import numpy as np
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from PokeTrack import pokemon_tracker

dir = sys.path[0]
faceCascade = cv2.CascadeClassifier(dir+'/models/cascade.xml')


class image_converter:
 
  def __init__(self):
    # self.image_pub = rospy.Publisher("/pokemon_go/searcher",Image)
 
    self.bridge = CvBridge()
    self.image_sub = rospy.Subscriber("/tb3_0/camera/image_raw",Image,self.callback)
    self.PokeTrack = pokemon_tracker(True)
    print('init converter')

    
  def detect(self):
    frame = self.image.copy()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    rect = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30,30),
        flags = cv2.IMREAD_GRAYSCALE
    )
    for (x, y, w, h) in rect:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    cv2.imshow('frame', frame)

  def callback(self,data):
    # print('invoke call back')
    try:
      image = self.bridge.imgmsg_to_cv2(data, "bgr8")
      self.image =imutils.resize(image, width=500)
      # self.image = cv2.resize(image, (300, 300))
      # resized = imutils.resize(image, width=300)
      # cv2.imshow("Image", image)
      # save figure
      # ratio = image.shape[0] / float(resized.shape[0])
      
    except CvBridgeError as e:
      print(e)
    self.detect()

    # cv2.setMouseCallback("image", self.saveImage)  # 鼠标事件的回调函数
    cv2.waitKey(3)

 
def main(args):
  ic = image_converter()
  rospy.init_node('image_converter', anonymous=True)
  try:
    rospy.spin()
  except KeyboardInterrupt:
    print("Shutting down")
  cv2.destroyAllWindows()
 
if __name__ == '__main__':
    main(sys.argv)
